package io.renren.modules.bs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.PageUtil;
import io.renren.common.utils.DeleteFileUtil;
import io.renren.common.utils.ExcelUtil;
import io.renren.common.utils.PageUtils;
import io.renren.modules.bs.dao.BsDepartmentPatientDao;
import io.renren.modules.bs.entity.BsDepartmentPatientEntity;
import io.renren.modules.bs.entity.BsDepartmentPatientImgEntity;
import io.renren.modules.bs.service.BsDepartmentPatientImgService;
import io.renren.modules.bs.service.BsDepartmentPatientService;
import io.renren.modules.bs.service.BsPatientService;
import io.renren.modules.bs.vo.BsDepartmentPatientPageVo;
import io.renren.modules.bs.vo.ExtraPatientVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("bsDepartmentPatientService")
public class BsDepartmentPatientServiceImpl extends ServiceImpl<BsDepartmentPatientDao, BsDepartmentPatientEntity> implements BsDepartmentPatientService {

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private BsPatientService patientService;

    @Autowired
    private BsDepartmentPatientImgService imgService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
//        Map<String, Object> params = new HashMap<>();
//        params.put("page",departmentPatientDto.getPage());
//        params.put("limit",departmentPatientDto.getLimit());
//        params.put("hospitalId",departmentPatientDto.getHospitalId());
//        params.put("startTime",departmentPatientDto.getStartTime());
//        params.put("endTime",departmentPatientDto.getEndTime());
//        params.put("isLeave",departmentPatientDto.getIsLeave());
//        params.put("departmentId",departmentPatientDto.getDepartmentId());
//        params.put("fromType",departmentPatientDto.getFromType());
        Integer total = this.baseMapper.getTotal(params);
        PageUtil.formatPageParams(params);
        List<BsDepartmentPatientPageVo> departmentPatientPageVoList = this.baseMapper.getPageList(params);

        if ("app".equals(params.get("fromType"))) {
            Set<Long> collect = departmentPatientPageVoList.stream().map(BsDepartmentPatientPageVo::getDepartmentPatientId).collect(Collectors.toSet());
            if (collect.size() > 0) {

                QueryWrapper<BsDepartmentPatientImgEntity> wrapper = new QueryWrapper<>();
                wrapper.in("department_patient_id", collect);
                wrapper.in("img_type", 1);
                List<BsDepartmentPatientImgEntity> list = this.imgService.list(wrapper);
                Map<Long, List<BsDepartmentPatientImgEntity>> patientImgList = list.stream().collect(Collectors.groupingBy(BsDepartmentPatientImgEntity::getDepartmentPatientId));
                for (BsDepartmentPatientPageVo departmentPatientPageVo : departmentPatientPageVoList) {
                    List<BsDepartmentPatientImgEntity> departmentPatientImgEntityList = patientImgList.get(departmentPatientPageVo.getDepartmentPatientId());
                    if (departmentPatientImgEntityList != null && departmentPatientImgEntityList.size() > 0) {
                        departmentPatientPageVo.setHospitalizedImg(departmentPatientImgEntityList.get(0).getPatientImg());
                    }
                }
            }
        }
        return PageUtil.getPageUtils(departmentPatientPageVoList, total, params);
    }

    @Override
    public List<ExtraPatientVo> getAllExtraData(List<Long> hospIdList, List<Long> deptIdList) {
        return this.baseMapper.getAllExtraData(hospIdList, deptIdList);
    }

    @Override
    public List<ExtraPatientVo> getAllHospData() {
        return this.baseMapper.getAllHospData();
    }

    @Override
    @Transactional
    public void removeModelByIds(List<Long> asList) {
        QueryWrapper<BsDepartmentPatientImgEntity> imgEntityQueryWrapper = new QueryWrapper<>();
        imgEntityQueryWrapper.in("department_patient_id", asList);
        imgEntityQueryWrapper.isNotNull("extract_detail_patient_id");
        List<BsDepartmentPatientImgEntity> departmentPatientImgEntities = this.imgService.list(imgEntityQueryWrapper);
        Set<Long> extraDepartmentPatientIdSet = departmentPatientImgEntities.stream().map(BsDepartmentPatientImgEntity::getDepartmentPatientId).collect(Collectors.toSet());
        if (extraDepartmentPatientIdSet.size() > 0) {
            asList.removeAll(extraDepartmentPatientIdSet);
        }
        if(asList.size() > 0){
            QueryWrapper<BsDepartmentPatientImgEntity> newImgEntityQueryWrapper = new QueryWrapper<>();
            newImgEntityQueryWrapper.in("department_patient_id", asList);
            List<BsDepartmentPatientImgEntity> list = this.imgService.list(newImgEntityQueryWrapper);
            for (BsDepartmentPatientImgEntity bsDepartmentPatientImgEntity : list) {
                boolean b = DeleteFileUtil.deleteFile(filePath + bsDepartmentPatientImgEntity.getPatientImg());
//                if (!b) {
//                    throw new RRException("删除旧文件失败");
//                }
            }
            this.imgService.remove(newImgEntityQueryWrapper);

            Collection<BsDepartmentPatientEntity> bsDepartmentPatientEntities = this.listByIds(asList);

            this.removeByIds(asList);

            Set<Long> collect = bsDepartmentPatientEntities.stream().map(BsDepartmentPatientEntity::getPatientId).collect(Collectors.toSet());
            this.patientService.removeByIds(collect);
        }
    }

    @Override
    public void export(Map<String, Object> params, HttpServletResponse response) {

//        Map<String, Object> paramsMap = new HashMap<>();

//        if(departmentPatientIds != null && departmentPatientIds.length > 0){
//            paramsMap.put("list",departmentPatientIds);
//        }
        List<BsDepartmentPatientPageVo> bsDepartmentPatientPageVos = this.baseMapper.exportList(params);
        //获取所有的主推
        for (BsDepartmentPatientPageVo bsDepartmentPatientPageVo : bsDepartmentPatientPageVos) {
            if (bsDepartmentPatientPageVo.getGender() != null) {
                if (bsDepartmentPatientPageVo.getGender() == 1) {
                    bsDepartmentPatientPageVo.setGenderValue("男");
                } else {
                    bsDepartmentPatientPageVo.setGenderValue("女");
                }
            }

        }
        // 生成Excel
        //excel标题
        // 生成Excel
        Integer isLeave = Integer.parseInt((String) params.get("isLeave"));
        //excel标题
        String[] title = {"医院", "科室", "患者名称", "性别", "身份证号", "病室号", "病床号", "住院时间", "出院时间", "其他信息", "备注"};
        //excel名称
        String fileName;
        String sheetName;
        if (isLeave == 0) {
            fileName = "抽取记录.xls";
            sheetName = "住院表";
        } else {
            fileName = "抽取记录.xls";
            sheetName = "出院记录";
        }
        //sheet名

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook1(sheetName, title, bsDepartmentPatientPageVos, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    }

    @Override
    public List<BsDepartmentPatientEntity> getListByDay(int i) {
        return this.baseMapper.getListByDay(i);
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}